<template>
  <app-page>
    <mxp-refresh-page ref="mxpRefreshPageRef" :queryData="queryList">
      <view style="z-index: 2; width: 100%; height: 140px; background: #000000"></view>
      <view style="position: absolute; top: 40px; z-index: 4; width: 670rpx; height: 220rpx; margin-left: 40rpx">
        <image
          src="/static/images/personal/vip-top-bg.jpg"
          mode="scaleToFill"
          style="position: absolute; top: 0; left: 0; width: 670rpx; height: 220rpx; border-radius: 10px"
        ></image>
        <view
          style="
            position: relative;
            z-index: 3;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            justify-content: center;
            height: 220rpx;
            padding: 15px;
          "
        >
          <view style="display: flex; flex-direction: row; justify-content: flex-start">
            <view
              style="
                box-sizing: content-box;
                width: 45px;
                height: 45px;
                border: 2px solid #ffffff;
                border-radius: 40px;
                box-shadow: 0 3px 6px 1px rgba(193, 67, 4, 0.19);
              "
            >
              <mxp-image
                width="45px"
                height="45px"
                borderRadius="40px"
                :src="userInfo?.avatar || '/static/images/logo1.svg'"
                errorSrc="/static/images/logo1.svg"
              ></mxp-image>
            </view>
            <view style="display: flex; flex: 1; flex-direction: column; justify-content: center; margin-left: 8px">
              <text style="font-size: 16px; font-weight: bold; color: #522700">{{ userInfo?.nickname || '短剧用户' }}</text>
              <text style="margin-top: 6px; font-size: 12px; color: #522700">{{ userInfo?.isVip ? `${userInfo?.vipExpireTime}到期` : '未开通会员' }}</text>
            </view>
          </view>
          <text style="margin-top: 15px; font-size: 12px; color: #522700">开通会员VIP，可以享受超多会员权益</text>
        </view>
      </view>
      <view style="position: relative; z-index: 3; margin-top: -55px; border-radius: 10px 10px 0 0" :style="{ background: defThemeColor.bgColor }">
        <view
          style="
            display: flex;
            flex-direction: row;
            align-items: center;
            justify-content: space-between;
            padding: 10px 15px;
            padding-top: 40px;
            margin-top: 45px;
          "
        >
          <view style="display: flex; flex-direction: row; align-items: center">
            <image src="/static/images/personal/ico_vip.png" mode="scaleToFill" style="width: 18px; height: 18px"></image>
            <text style="margin-left: 4px; font-size: 16px; font-weight: bold; color: #000000">VIP专享会员权益</text>
          </view>
          <view hoverClass="hover" style="padding: 4px 0" @click="openPayNoticePopup">
            <text style="margin-left: 4px; font-size: 14px; color: #522700">《VIP服务协议》</text>
          </view>
        </view>
        <view class="weal-list">
          <view class="weal-item">
            <view class="weal-img-box">
              <image class="weal-img" src="/static/images/personal/icon-weal-list01.svg" mode="scaleToFill"></image>
            </view>
            <text class="weal-text">免费看</text>
          </view>
          <view class="weal-item">
            <view class="weal-img-box">
              <image class="weal-img" src="/static/images/personal/icon-weal-list02.svg" mode="scaleToFill"></image>
            </view>
            <text class="weal-text">减免广告</text>
          </view>
          <view class="weal-item">
            <view class="weal-img-box">
              <image class="weal-img" src="/static/images/personal/icon-weal-list03.svg" mode="scaleToFill"></image>
            </view>
            <text class="weal-text">享折扣</text>
          </view>
          <view class="weal-item">
            <view class="weal-img-box">
              <image class="weal-img" src="/static/images/personal/icon-weal-list04.svg" mode="scaleToFill"></image>
            </view>
            <text class="weal-text">福利优惠</text>
          </view>
        </view>
        <view style="display: flex; align-items: center; padding: 8px 15px; margin: 15px; background: #fff8f2; border-radius: 6px">
          <image src="/static/images/personal/ico_notification.svg" mode="scaleToFill" style="width: 16px; height: 16px"></image>
          <text style="margin-left: 6px; font-size: 14px; color: #522700">精心为你打造专属权益，欢迎加入VIP会员~</text>
        </view>
        <template v-if="payList.length > 0">
          <view class="pay-list">
            <pay-select-item
              v-for="(item, index) in payList"
              :key="index"
              style="width: 100%"
              :productType="2"
              :active="currIndex === index"
              :productName="item.productName || ''"
              :productPrice="isToutiao && devicePlatform === 'ios' ? (item.productPrice || 0) * 10 : item.productPrice || 0"
              :marketingDesc="item.marketingDesc || ''"
              :recommendTags="item.recommendTags || ''"
              :unit="isToutiao && devicePlatform === 'ios' ? '钻' : '元'"
              @myClick="changeMoney(index)"
            ></pay-select-item>
          </view>
          <view class="hint-box">
            <text class="title">温馨提示：</text>
            <text class="hint">1. 虚拟物品付费后不支持退款</text>
            <text class="hint">2. K币充值后不可反向兑换为人民币等其他法定货币</text>
            <text class="hint">3. 会员有效期内可免费观看无需付费解锁，会员过期后无法观看(已付费解锁剧集除外)</text>
            <text class="hint">4. 未满18岁的未成年,应在监护人同意或授权下充值</text>
            <text class="hint">5. 在播剧目{{ dramaOnlineNum }}部</text>
          </view>
        </template>
        <view style="height: 100px"></view>
      </view>
    </mxp-refresh-page>
    <!-- #ifdef MP-TOUTIAO -->
    <service-button :offsetTop="15" :location="['15px', '95px']"></service-button>
    <!-- #endif -->
    <!-- VIP服务协议 -->
    <membership-agreement-popup ref="membershipAgreementPopupRef" :height="sys.windowHeight * 0.7"></membership-agreement-popup>
  </app-page>
</template>

<script setup lang="ts">
  import AppPage from '@/components/app-page/app-page.vue';
  import { computed, ref } from 'vue';
  // #ifdef MP-TOUTIAO
  import ServiceButton from '@/components/pay/service-button/service-button.vue';
  // #endif
  import MembershipAgreementPopup from '@/components/page/membership-agreement/membership-agreement-popup.vue';
  import PaySelectItem from '@/components/pay/pay-select-item/pay-select-item.vue';
  import {
    type RechargeService,
    createWebRechargeOrderAxios,
    createWechatDramaOrderAxios,
    dyCreateEpisodePayOrderAxios,
    getVirtualProductListAxios,
    queryOrderAxios,
  } from '@/api/pay';
  import MxpImage from '@/mxp-ui/mxp-image/mxp-image.vue';
  import { ksPay, ttOrderPay, webPay, wxOrderPay, wxOrderVirtualPay } from '@/utils/payUtil';
  import { useAppStore } from '@/pinia/app';
  import mxpGetSysInfoStore from '@/mxp-ui/mxp-tool/store/mxp-store-sys-info';
  import type { UserInfo } from '@/api/user';
  import { defThemeColor } from '@/mxp-ui/mxp-tool/theme/theme';
  import { sleep } from '@/mxp-ui/mxp-tool/utils/rest';
  import { updateUserInfo } from '@/utils/page/user';
  import { onPullDownRefresh } from '@dcloudio/uni-app';

  import MxpRefreshPage, { type Ins } from '@/mxp-ui/mxp-refresh-page/mxp-refresh-page.vue';
  import { useRefresh } from '@/mxp-ui/mxp-tool/hooks/useHooksRefresh.ts';

  const { mxpRefreshPageRef } = useRefresh(onPullDownRefresh);

  const sys = mxpGetSysInfoStore().getSysInfo();

  const membershipAgreementPopupRef = ref<InstanceType<typeof MembershipAgreementPopup> | null>(null);
  const appStore = useAppStore();
  const userInfo = computed<UserInfo | undefined>(() => appStore.userInfo);
  const payList = ref<RechargeService[]>([]);
  const currIndex = ref(-1);
  const loading = ref(false);
  const priceVirtualRate = ref('');
  const isPay = ref(true);
  const dramaOnlineNum = ref(0);
  const devicePlatform = computed(() => (sys.value.platform === 'devtools' ? sys.value.osName : sys.value.platform));
  const isToutiao = computed(() => sys.value.uniPlatform === 'mp-toutiao');

  /** 切换支付 */
  async function changeMoney(index: number) {
    if (!loading.value) {
      currIndex.value = index;
      if (isPay.value) {
        const item = payList.value[currIndex.value]!;
        try {
          loading.value = true;
          // #ifdef MP-TOUTIAO
          await openTTPay(item.productId);
          // #endif

          // #ifdef MP-WEIXIN
          await openWxPay(item.productId);
          // #endif

          // #ifdef MP-KUAISHOU
          await openKsPay(item.productId);
          // #endif

          // #ifdef WEB
          await openWebPay(item.productId);
          // #endif

          // #ifdef APP
          await openAppPay(item.productId);
          // #endif
          loading.value = false;

          // #ifndef WEB
          uni.showToast({ title: '充值成功', icon: 'success', position: 'bottom' });
          // #endif
        } catch (error) {
          console.log('充值失败====', error);
          // #ifndef WEB
          uni.showToast({ title: '充值失败', icon: 'none', position: 'bottom' });
          // #endif
          loading.value = false;
        }
      } else {
        uni.showToast({ title: '由于平台限制,暂不支持支付', icon: 'none', position: 'bottom' });
      }
    }
  }

  /** 微信支付 */
  async function openWxPay(productId?: number | undefined) {
    // #ifdef MP-WEIXIN
    try {
      uni.showLoading({ title: '加载中', mask: true });
      const wxOrder = await createWechatDramaOrderAxios({
        referralLinkId: appStore.launchQuery?.referralLinkId,
        wxExportId: appStore.launchQuery?.wxExportId,
        wxFinderId: appStore.launchQuery?.wxFinderId,
        wxPromotionId: appStore.launchQuery?.wxPromotionId,
        channelId: appStore.launchQuery?.channelId,
        productType: 2,
        clickId: appStore.launchQuery?.clickid,
        productId,
        devicePlatform: sys.value.platform === 'devtools' ? sys.value.osName : sys.value.platform,
        launchQueryPramas: appStore.newLaunchQuery || {},
      });
      uni.hideLoading();
      if (devicePlatform.value === 'ios') {
        await wxOrderPay(wxOrder.data.paymentDTO!);
      } else {
        await wxOrderVirtualPay(wxOrder.data);
      }
      uni.showLoading({ title: '正在获取支付结果', mask: true });
      await queryPaymentResults(wxOrder.data.outTradeNo!);
      uni.hideLoading();
      return Promise.resolve(true);
    } catch (error) {
      uni.hideLoading();
      return Promise.reject(error);
    }
    // #endif
  }

  /** 快手支付 */
  async function openKsPay(productId?: number | undefined) {
    // #ifdef MP-KUAISHOU
    try {
      uni.showLoading({ title: '加载中', mask: true });
      const ksOrder = await createWebRechargeOrderAxios({
        referralLinkId: appStore.launchQuery?.referralLinkId,
        productType: 2,
        productId,
        devicePlatform: devicePlatform.value,
      });
      uni.hideLoading();
      await ksPay({ order_no: ksOrder.data.transactionId!, order_info_token: ksOrder.data.orderInfoToken! });
      uni.showLoading({ title: '正在获取支付结果', mask: true });
      await queryPaymentResults(ksOrder.data.outTradeNo!);
      uni.hideLoading();
      return Promise.resolve(true);
    } catch (error) {
      uni.hideLoading();
      return Promise.reject(error);
    }
    // #endif
  }

  /** 抖音小程序支付 */
  async function openTTPay(productId?: number | undefined): Promise<boolean> {
    // #ifdef MP-TOUTIAO
    try {
      uni.showLoading({ title: '加载中', mask: true });
      const ttOrder = await dyCreateEpisodePayOrderAxios({
        referralLinkId: appStore.launchQuery?.referralLinkId,
        channelId: appStore.launchQuery.channelId || undefined,
        productType: 2,
        devicePlatform: devicePlatform.value,
        clickId: appStore.launchQuery?.clickid,
        productId,
        launchQueryPramas: appStore.launchQuery || {},
      });
      const payResult = await ttOrderPay(ttOrder.data);
      uni.showLoading({ title: '正在获取支付结果', mask: true });
      await queryPaymentResults(payResult.outTradeNo!);
      uni.hideLoading();
      return Promise.resolve(true);
    } catch (error) {
      uni.hideLoading();
      return Promise.reject(error);
    }
    // #endif
  }

  /** 网页支付 */
  async function openWebPay(productId?: number | undefined) {
    // #ifdef WEB
    try {
      const webOrder = await createWebRechargeOrderAxios({
        referralLinkId: appStore.launchQuery?.referralLinkId,
        productType: 2,
        productId,
        devicePlatform: devicePlatform.value,
      });
      webPay(webOrder.data.alipayForm!);
      return Promise.resolve(true);
    } catch (error) {
      return Promise.reject(error);
    }
    // #endif
  }
  /** APP支付 */
  async function openAppPay(productId?: number | undefined): Promise<boolean> {
    // #ifdef APP
    try {
      const order = await createWebRechargeOrderAxios({
        referralLinkId: appStore.launchQuery?.referralLinkId,
        productType: 1,
        productId,
        devicePlatform: sys.value.platform === 'devtools' ? sys.value.osName : sys.value.platform,
      });
      //  await pay(order.data);
      await queryPaymentResults(order.data.outTradeNo!);
      return Promise.resolve(true);
    } catch (error) {
      return Promise.reject(error);
    }
    // #endif
  }

  /** 打开充值须知 */
  function openPayNoticePopup() {
    membershipAgreementPopupRef.value?.show();
  }

  /** 加载中 */
  async function queryList(ins?: Ins) {
    try {
      const res = await getVirtualProductListAxios({
        productType: 2,
        referralLinkId: appStore.launchQuery?.referralLinkId,
        devicePlatform: devicePlatform.value,
        wxFinderId: appStore.launchQuery?.wxFinderId,
        wxExportId: appStore.launchQuery?.wxExportId,
        wxPromotionId: appStore.launchQuery?.wxPromotionId,
      });
      priceVirtualRate.value = appStore.baseDictInfo?.PRICE_VIRTUAL_RATE || '未知';
      payList.value = res.data.productList || [];
      currIndex.value = res.data.selectIndex;
      dramaOnlineNum.value = res.data.dramaOnlineNum;
      isPay.value = res.data.pay;
      ins?.setSuccess();
    } catch (error) {
      payList.value = [];
      ins?.setMoreEmpty('fail_load', error.msg || '获取数据失败，BD0001');
    }
  }

  /**
   * 查询支付结果,并更新用户信息(K币和会员状态)
   */
  async function queryPaymentResults(outOrderNo: string) {
    try {
      await sleep(1000);
      const queryRes = await queryOrderAxios(outOrderNo);
      if (queryRes.data.status === 1) {
        await updateUserInfo(); // 更新个人资料
        return Promise.resolve(true);
      } else {
        return Promise.resolve(false);
      }
    } catch (error) {
      return Promise.resolve(false);
    }
  }
</script>

<style lang="scss" scoped>
  .weal-list {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 0 15px;
    margin-top: 15px;

    .weal-item {
      display: flex;
      flex-direction: column;

      .weal-img-box {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
        width: 52px;
        height: 52px;
        background: #fffbf3;
        border-radius: 12px;

        .weal-img {
          width: 24px;
          height: 24px;
        }
      }

      .weal-text {
        margin-top: 8px;
        font-size: 14px;
        color: #000000;
      }
    }
  }

  .pay-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 15px;
    justify-content: space-between;
    justify-items: center;
    padding: 15px;
  }

  .hover {
    opacity: 0.7;
  }

  .hint-box {
    display: flex;
    flex-direction: column;
    padding: 15px;
    padding-top: 0;

    .title {
      margin-bottom: 6px;
      font-size: 12px;
      font-weight: bold;
      color: #666666;
      word-break: break-all;
      word-wrap: break-word;
      white-space: normal !important;
    }

    .hint {
      margin-bottom: 6px;
      font-size: 12px;
      color: #999999;
      word-break: break-all;
      word-wrap: break-word;
      white-space: normal !important;
    }
  }
</style>
